package com.snoob.lixing.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 日期工具类: 完成日期与日期字符串之间的相互转化
 * <p>
 * yyyy-MM-dd HH:mm:ss
 */
public class DateUtil {

    public static void main(String[] args) {
        System.out.println(dateToString(new Date()));
        System.out.println(stringToDate("2012-12-13 00:00:00.0"));
    }

    /**
     * 将Date转成String
     */
    public static String dateToString(Date date, String pattern) {
        if (date != null && pattern != null && pattern != "") {
            return new SimpleDateFormat(pattern).format(date);
        }
        return "";
    }

    public static String dateToString(Date date) {
        return dateToString(date, "yyyy-MM-dd");
    }

    /**
     * 将String转化成Date
     */
    public static Date stringToDate(String date, String pattern) {
        try {
            if (date != null && date != "" && pattern != null && pattern != "") {
                return new SimpleDateFormat(pattern).parse(date);
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static Date stringToDate(String date) {
        try {
            if (date != null && date != "") {
                return new SimpleDateFormat("yyyy-MM-dd").parse(date);
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

}
